<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        input{
            width: 250px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-bottom: 10px;
        }

        .btn{
            width: 150px;
        }

        .tip{
            color: #ff0000;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div>
        <h1>用户注册</h1>
        <form >
            用户名:
            <input type="text" id="username" name="username" placeholder="用户名不能为空且长度在4-16">
            <span class="tip" id="name_msg"></span><br>

            手机号:
            <input type="text" id="phone" name="phone" placeholder="手机号不能为空且为十一位">
            <span class="tip" id="phone_msg"></span><br>
            <br>

            <input type="submit" value="提交" class="btn">
            <input type="reset" value="重置" class="btn">

        </form>
    </div>


    <script>
        //需求：表单检验--用户名：长度在4-16位；手机号：长度11位
        //分析：JS事件--鼠标离焦事件blur，表单提交事件submit
        //校验用户名
        //1.获取用户名
        let input = document.querySelector("#username");

        let checkUsername = ()=>{
            let flag =true;  //用来标识用户名是否合法
            let usernameValue = input.value;
            

            //校验用户名的长度
            if(usernameValue.length<4||usernameValue.length>16){
                document.querySelector("#name_msg").innerHTML = "用户名不合法！"
                flag = false;
            }else{
                document.querySelector("#name_msg").innerHTML = ""
            }

            return flag;
        }

        input.addEventListener('blur',checkUsername);

        //校验手机号
        let input2 = document.querySelector("#phone");
        let checkphone = ()=>{
            let phoneValue = input2.value;
            let flag = true;

            if(phoneValue.length != 11){
                document.querySelector("#phone_msg").innerHTML = "手机号不合法！"
                flag = false;
            }else{
                document.querySelector("#phone_msg").innerHTML = ""
                
            }

            return flag;
        }

        input2.addEventListener('blur',checkphone);

        //表单提交时校验
        document.querySelector("form").addEventListener("submit",(event)=>{
            if(!checkUsername()||!checkphone()){
                alert("用户名或手机号不合法！");
            //阻止表单提交
            event.preventDefault();
            }
            
        })

    </script>
</body>
</html>